/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.cs.util.http;

import com.cs.util.collection.MultiValuedMap;
import java.util.List;
import java.util.Map;

/**
 * QueryString can be used for parsing an URI querystring.
 * The querystring of an URI is the part between the ? and the end of the URI.
 * @author dimitris@jmike.gr
 */
public class QueryString extends MultiValuedMap<String, String> {

    /**
     * Parses the specified String and constructs a new QueryString.
     * @param querystring the part between the ? and the end of the URI.
     */
    public QueryString(String querystring) {
        super();
        if (querystring != null) {//querystring is not null
            final String[] segments = querystring.split("&");//split querystring at '&'
            for (int i = 0; i < segments.length; i++) {//iterate segments
                String[] kv = segments[i].split("=", 2);////split segment at '='
                if (kv.length >= 2) {//kv contains key and value
                    super.add(kv[0], kv[1]);
                } else {//kv contains only name
                    super.add(kv[0], "");
                }
            }
        }
    }

    /**
     * Constructs a new QueryString from an existing Map.
     * @param map a map containing multiple values for each key.
     */
    public QueryString(Map<String, List<String>> map) {
        super();
        super.putAll(map);
    }
}
